const app = getApp()
var wh = require("../../utils/wh.js");
var WxParse = require('../../wxParse/wxParse.js');
// pages/details/details.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [{
      id: 1,
      img: '../../img/banner.png'
    },
    {
      id: 2, 
      img: '../../img/banner.png'
    },
    {
      id: 3,
      img: '../../img/banner.png'
    },
    ],
    morelists: [],
    istrue: true,
    index: '1',
    allImg: '',
    notcut: false,
    seckill_id:'',
    cutdown: {
      'hh': 0,
      'dd': 0,
      'mm': 0,
      'ss': 0
    }, //倒计时
    setintvalid: null,
    seckillInfo: '',
    goodsInfo: '',
    ShopDetail: '',
    CollectHave: '',
    likeNum: '',
    ShareCount:'',
    buyuserList:'',//抢购成功列表
    buyusertotal: '',
    status:'',//该商品秒杀情况
    onearth: false,
    pagea: 1,
    page_sizea: 5,
    comments: [],
    cutdaowbefore: false,
    user_just: '',
    maskHidden: false, // 海报
    have: true,
    url: '',
    is_order: ''
  },
  nav() {
    this.setData({
      no_data: 0,
      pagea: 1,
      page_sizea: 5,
      onearth: false,
      comments: [],
      have: true,
    });
    this.good_comments()
    let istrue = this.data.istrue
    this.setData({
      istrue: !istrue 
    })
  },
  bindchange: function (e) {
    this.setData({
      index: e.detail.current + 1,
    })
  },
  // 获取商品评价列表
  good_comments() {
    let that = this;
    let page_size = this.data.page_sizea,
      no_data = this.data.no_data,
      page = this.data.pagea;
    if (no_data == 0) {
      wh.Post('/api/mall.comment/good_comments', {
        page: page,
        page_num: page_size,
        goods_id: that.data.seckillInfo.goods_id
      }, function (res) {
        console.log('商品评价列表', res)
        let shop = that.data.comments.concat(res.list),
          count = res.list.length;
        if (page_size > count) {
          that.data.no_data = 1;
          if (shop.length > 1) {
            that.setData({
              onearth: true
            })
          }
        }
        that.setData({
          comments: shop
        })
        if (that.data.comments.length == 0) {
          that.setData({
            have: false,
          });
        } else {
          that.setData({
            have: true,
          });
        }
      })
    }
  },
  // 获取抢购成功列表
  buyuser(seckill_id){
    var that = this;
    wh.Post('/api/mall.seckill/buyuser', {
      seckill_id: seckill_id,
      page: 1,
      page_num:5
    }, function (res) {
      console.log('抢购成功列表', res)
      that.setData({
        buyuserList: res.list,
        buyusertotal: res.total,
      })
    });
  },
  // 获取我的秒杀活动信息
  mysec(seckill_id){
    var that = this;
    wh.Post('/api/mall.seckill/mysec', {
      seckill_id: seckill_id,
    }, function (res) {
      console.log('我的秒杀活动', res)
      that.setData({
        status: res
      })
    });
  },
  // 查看是否收藏
  CollectHave(goods_id) {
    var that = this;
    wh.Post('/api/mall.collect/have', {
      target_id: goods_id,
      type: 1
    }, function (res) {
      console.log('是否收藏', res)
      that.setData({
        CollectHave: res
      })
    });
  },
  // 收藏提交
  CollectSubmit() {
    var that = this;
    wh.Post('/api/mall.collect/submit', {
      target_id: that.data.seckillInfo.goods_id,
      type: 1
    }, function (res) {
      that.ColletcTotal(that.data.seckillInfo.goods_id)
      let CollectHave = !that.data.CollectHave;
      that.setData({
        CollectHave: CollectHave
      })
    })
  },
  // 获取收藏喜欢统计
  ColletcTotal(goods_id) {
    var that = this;
    wh.Post('/api/mall.collect/total', {
      target_id: goods_id,
      type: 1
    }, function (res) {
      that.setData({
        likeNum: res
      })
    })
  },
  // 获取商家店铺详情
  getShopDetail(shop_id) {
    var that = this;
    wh.Post('/api/mall.shop/detail', {
      shop_id: shop_id
    }, function (res) {
      console.log('店铺详情', res)
      that.setData({
        ShopDetail: res,
      })
    });
  },
   // 获取店铺分享统计信息
  getShareCount(shop_id) {
    var that = this;
    wh.Post('/api/mall.share/get_count', {
      shop_id: shop_id
    }, function (res) {
      console.log('获取店铺分享统计信息', res)
      that.setData({
        ShareCount: res,
      })
    });
  },
  // 更多经典
  morelists(shop_id) {
    let that = this;
    wh.Post('/api/mall.goods/lists', {
      shop_id: shop_id,
      is_recom: 1,
      is_hot: 1
    }, function (res) {
      that.setData({
        morelists: res
      })
      console.log('更多经典', res)
    })
  },
  // 记录用户访问足迹
  FootMarkRecord(shop_id) {
    wh.Post('/api/mall.footmark/record', {
      shop_id: shop_id,
      target_id: shop_id,
      type: 1
    }, function (res) {

    })
  },
  // 获取秒杀详情
  getSeckillDetail(seckill_id) {
    let that = this;
    wh.Post('/api/mall.seckill/detail', {
      seckill_id: seckill_id
    }, function (res) {
      // that.FootMarkRecord(res.seckill.shop_id)
      that.morelists(res.seckill.shop_id)
      that.getShareCount(res.seckill.shop_id)
      that.getShopDetail(res.seckill.shop_id)
      that.CollectHave(res.seckill.goods_id)
      that.ColletcTotal(res.seckill.goods_id)
      if (res.goods.goods_info) { 
        WxParse.wxParse('goods_detail', 'html', res.goods.goods_info, that)
      };
      clearInterval(that.setintvalid); //清除倒计时
      let thistime = new Date().getTime(); //判断时间
      let start_time = res.seckill.start_time + '000'; //精确到毫秒数 
      let end_time = res.seckill.end_time + '000'; //精确到毫秒数 
      if (thistime <= start_time) { //当前时间小于开始时间 活动未开始
        that.start_bargain(start_time, thistime, end_time);
      } else if (thistime < end_time) { //当前时间小于结束时间 活动进行中
        that.end_bargain(end_time, thistime);
      } else {
        that.setData({
          notcut: true
        }); //活动结束
      }
      console.log('秒杀详情', res)
      that.setData({
        seckillInfo: res.seckill,
        goodsInfo: res.goods,
        is_order: res.is_order,
        allImg: res.goods.cover_album.length
      })
    })
  },
  //活动未开始
  start_bargain: function (start_time, thistime, end_time) {

    let that = this;
    let cha = start_time - thistime; //开始时间减去现在时间
    that.setData({
      cutdaowbefore: true
    });
    that.setintvalid = setInterval(function () {
      cha -= 1000;
      if (cha <= 0) {
        clearInterval(that.setintvalid);
        cha = 0;
        that.end_bargain(end_time, thistime);
      }
      that.time_meter(cha);
    }, 1000);
  },

  //活动已开始
  end_bargain: function (end_time, thistime) {
    let cha = end_time - thistime;
    let that = this;

    that.setData({
      cutdaowbefore: false
    })

    that.setintvalid = setInterval(function () {
      cha -= 1000;
      if (cha <= 0) {
        clearInterval(that.setintvalid);
        cha = 0;
        that.setData({
          notcut: true
        });
        return;
      }
      that.time_meter(cha)
    }, 1000);
  },
  //时间计算
  time_meter: function (timer) {
    let that = this;
    let dd = parseInt(timer / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
    let hh = parseInt(timer / 1000 / 60 / 60 % 24, 10); //计算剩余的小时数
    let mm = parseInt(timer / 1000 / 60 % 60, 10); //计算剩余的分钟数
    let ss = parseInt(timer / 1000 % 60, 10); //计算剩余的秒数
    mm = that.checkTime(mm);
    ss = that.checkTime(ss);
    let cutdown = {
      'dd': dd,
      'hh': hh,
      'mm': mm,
      'ss': ss
    };
    that.setData({
      cutdown: cutdown
    })
  },
  checkTime: function (i) {
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  },
  // 记录店铺分享
  RecordShare() {
    let that = this;
    wh.Post("/api/mall.share/record_share", { shop_id: that.data.seckillInfo.seckill.shop_id }, function (res) {
      that.getShareCount(that.data.seckillInfo.seckill.shop_id)
    })
  },
  // 提交预约
  SeckillNotice(e){
    let that = this;
    wh.Post('/api/mall.seckill/notice', {
      target_id: that.data.seckill_id,
      form_id: e.detail.formId
    }, function (res) {
      that.setData({
        is_order:1
        })
    })
  },
  // 立即秒杀
  btnSeckill(){
    let that = this,
      status = this.data.status;
    wh.Post('/api/mall.seckill/grab', {
      seckill_id: that.data.seckill_id,
    }, function (res) {
      console.log('立即秒杀',res)
      if (res.pay==0){
      wx.navigateTo({
        url: '../submit/submit?user_sec_id=' + res.sponsor_id + '&istype=' + 3,
      })
      } else if (res.pay == 1){
        wx.showModal({
          title: '您已购买过该秒杀商品',
        })
      }
    })
  },
  // 刚刚秒杀购买了商品
  user_just(seckill_id) {
    let that = this;
    wh.Post('/api/mall.seckill/just', {
      seckill_id: seckill_id
    }, function (res) {
      console.log('某某某刚刚秒杀购买了商品', res)
      that.setData({
        user_just: res
      })
    })
  },
  // 获取url
  url() {
    let that = this;
    wx.getExtConfig({
      success: function (res) {
        console.log(2, res)
        let url = res.extConfig.apiurl;
        that.setData({
          url: url
        })
      }
    })
  },
  /** 
 * 生成海报
 */
  createPoster: function () {
    let param = this.data.seckillInfo,
      url = this.data.url,
      that = this,
      postUrl = '/api/mall.ajax/page_qrcode',
      tag = '秒杀',
      s_url = 'pages/killDetails/killDetails?seckill_id=' + this.data.seckillInfo.seckill_id;
    setTimeout(() => {
      wx.showToast({
        title: '海报生成中...',
        icon: "loading",
      });
      setTimeout(() => {
        wx.hideToast();
      }, 10000)
    }, 0);
    param.title = param.seckill_title;
    param.goods_desc = param.seckill_desc;
    param.price = param.seckill_price;
    param.market_price = param.original_price;
    // 获取小程序码
    wh.Post(postUrl, { s_url: s_url }, function (imgUrl) {
      console.log(imgUrl)
      // 将图片保存到本地
      wx.getImageInfo({
        src: param.seckill_cover,   //请求的网络图片路径
        success: function (res1) {
          param.path1 = res1.path;
          wx.getImageInfo({
            src: imgUrl,    //请求的网络图片路径
            success: function (res2) {
              param.path2 = res2.path;
              // 开始绘制
              app.startToDraw(param, url, tag, imgUrl);
              that.setData({
                maskHidden: true
              });
              // 将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
              setTimeout(function () {
                // wx.hideLoading()
                wx.canvasToTempFilePath({
                  canvasId: 'mycanvas',
                  success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    that.setData({
                      imagePath: tempFilePath,
                      canvasHidden: true
                    });
                  },
                  fail: function (res) {
                    console.log(res);
                  }
                });
              }, 200);
            }
          });
        }
      });
    });
  },
  /**
   * 点击保存到相册
   */
  poster_save: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        that.setData({
          maskHidden: false
        });
        wx.showToast({
          title: '图片已保存到相册',
        });
      }
    })
  },
  /**
   * 关闭海报
   */
  close_share: function () {
    this.setData({
      maskHidden: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.url()
    this.getSeckillDetail(options.seckill_id)
    this.buyuser(options.seckill_id)
    this.user_just(options.seckill_id)
    this.mysec(options.seckill_id)
    this.setData({
      seckill_id: options.seckill_id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.app_auth(this)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let no_data = this.data.no_dataa,
      page = this.data.page,
      page_size = this.data.page_sizea;
    if (no_data == 0) {
      this.data.page = page + 1;
      this.good_comments()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    return {
      title: that.data.seckillInfo.seckill_title,
      path: '/pages/killDetails/killDetails?seckill_id=' + that.data.seckill_id,
      imageUrl: that.data.seckillInfo.seckill_cover,
      success: function (res) {
        that.RecordShare()
        console.log('转发成功')
      }
    }
  }
})